<template>

     <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="formInline.AppName" placeholder="请填写名称" clearable />
    </el-form-item>
    
     <el-form-item label="审批状态">
      <el-select
        v-model="formInline.ApprovalState"
        placeholder="请选择状态"
        clearable
      >
        <el-option label="待审核" :value="false" />
        <el-option label="已审核" :value="true" />
      </el-select>
    </el-form-item>

    <el-form-item label="时间">
      <el-date-picker
        v-model="formInline.Start"
        type="date"
        placeholder="请选择开始时间"
        clearable
      />- <el-date-picker
        v-model="formInline.End"
        type="date"
        placeholder="请选择结束时间"
        clearable
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getdata"  color="#33B5BA" style="color: #FFF;">查询</el-button>
    </el-form-item>
  </el-form>
<el-button @click="dialogFormVisible=true;" type="success" v-if="!(pinia.account.names as string[]).includes(pinia.account.UserName)">新增</el-button>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column  type="index" label="序号" width="80" />
    <el-table-column prop="appName" label="姓名" width="100" />
    <el-table-column prop="departmentId" label="部门" width="100"  :formatter="departname" />
    <el-table-column prop="sorts" label="请假类别" width="100" />
    <el-table-column prop="startTime" label="请假时间" width="220" >
         <template v-slot="scope">
            {{ moment(scope.row.startTime).format('YYYY-MM-DD') }} 至 {{ moment(scope.row.endTime).format('YYYY-MM-DD') }}
        </template>
    </el-table-column>
    <el-table-column prop="totalTime" label="总工时(H)" width="90" />
    <el-table-column prop="reportTime" label="报道时间" width="120" >
        <template v-slot="scope">
            {{ moment(scope.row.reportTime).format('YYYY-MM-DD') }}
        </template>
    </el-table-column>
    <el-table-column prop="reason" label="请假事由" width="120" />
    <el-table-column prop="headName" label="部门领导" width="120" />
    <el-table-column prop="approvalState" label="审批状态" width="120" >
        <template v-slot="scope">
            {{ scope.row.approvalState==false?'待审核':'已审核' }}
        </template>
    </el-table-column>

   

    <el-table-column prop="createTime" label="创建时间" width="120" >
         <template v-slot="scope">
            {{ moment(scope.row.createTime).format('YYYY-MM-DD') }}
        </template>
    </el-table-column>

    <el-table-column prop="approvalReason" label="拒绝原因" width="120" />

    <el-table-column fixed="right" label="操作" min-width="200">
      <template #default="scope">
        <el-button  type="primary" size="small" plain @click="update(scope.row)" v-if="scope.row.approvalState==false">
          修改
        </el-button>
        <el-button  type="danger" size="small" plain v-if="scope.row.approvalState==false" @click="del(scope.row.id)">删除</el-button>
        <el-button  type="warning" size="small" plain v-if="scope.row.approvalState==false"  @click="UpdState(scope.row)">审核</el-button>
      </template>
    </el-table-column>
  </el-table>

  <table>
    <tr>
        <td>
             <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="pages.PageIndex"
      v-model:page-size="pages.PageSize"
      :page-sizes="[15,20,25]"
      :size="size"
      layout="slot"
      :total="pages.totalCount"
    ><span>共{{ pages.totalCount }}条，每页{{ pages.PageSize }}条，当前{{ pages.PageIndex }}/{{ pages.totalPage }}页</span>
</el-pagination>
  </div>
        </td>
        <td>
               <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="pages.PageIndex"
      v-model:page-size="pages.PageSize"
      :page-sizes="[15,20,25]"
      :size="size"
      layout="slot, prev, pager, next"
      :total="pages.totalCount"
      prev-text="上一页"
      next-text="下一页"
    ><el-button @click="pages.PageIndex=1">首页</el-button>
</el-pagination>
  </div>
        </td>
        <td>
               <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="pages.PageIndex"
      v-model:page-size="pages.PageSize"
      :page-sizes="[15,20,25]"
      :size="size"
      layout="slot, sizes,  jumper"
      :total="pages.totalCount"
       prev-text="上一页"
      next-text="下一页"
    ><el-button @click="pages.PageIndex=pages.totalPage">尾页</el-button>
</el-pagination>
  </div>
        </td>
    </tr>
  </table>

   <el-dialog v-model="dialogFormVisible" title="新增申请" width="800">
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px;"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="姓名" prop="appName">
      <el-input v-model="ruleForm.appName" :disabled="true" />
    </el-form-item>

     <el-form-item label="部门" prop="region">
      <el-select v-model="ruleForm.departmentId" placeholder="请选择部门" :disabled="true">
        <el-option label="IT信息部" :value="1" />
        <el-option label="人力资源部" :value="2" />
          <el-option label="财务部" :value="3" />
        <el-option label="销售部" :value="4" />
      </el-select>
    </el-form-item>



     <el-form-item label="请假类别" >
      <el-checkbox-group v-model="ruleForm.sortss">
        <el-checkbox value="事假" name="sorts">
         事假
        </el-checkbox>
        <el-checkbox value="病假" name="sorts">
          病假
        </el-checkbox>
        <el-checkbox value="婚假" name="sorts">
          婚假
        </el-checkbox>
        <el-checkbox value="丧假" name="sorts">
          丧假
        </el-checkbox>
        <el-checkbox value="产假" name="sorts">
         产假
        </el-checkbox>
        <el-checkbox value="补休" name="sorts">
          补休
        </el-checkbox>
        <el-checkbox value="工伤" name="sorts">
          工伤
        </el-checkbox>
        <el-checkbox value="其它" name="sorts">
          其它
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
   

        
            <el-form-item label="请假时间" >
                 <el-date-picker
                v-model="ruleForm.startTime"
                type="datetime"
                placeholder="请选择开始时间" @change="calculateTotalTime"
                />-
                <el-date-picker
                v-model="ruleForm.endTime"
                type="datetime"
                placeholder="请选择结束时间"
                @change="calculateTotalTime"
                />
              
                <el-col :span="15">共计{{ ruleForm.days }} </el-col>
                <br/><br/>

                 <el-form-item label="报道时间" >
                <el-date-picker
                v-model="ruleForm.reportTime"
                type="datetime"
                placeholder="请选择报道时间"
                />
            </el-form-item>
            </el-form-item>
            

    <el-form-item label="请假事由" prop="reason">
      <el-input v-model="ruleForm.reason" type="textarea" />
    </el-form-item>

     <el-form-item label="部门领导" prop="headName">
      <el-input v-model="ruleForm.headName"  :disabled="true"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForms(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
   </el-dialog>

 <el-dialog v-model="dialogFormVisibleedit" title="修改申请" width="800">
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px;"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="姓名" prop="appName">
      <el-input v-model="ruleForm.appName" :disabled="true" />
    </el-form-item>

     <el-form-item label="部门" prop="region">
      <el-select v-model="ruleForm.departmentId" placeholder="请选择部门" :disabled="true">
        <el-option label="IT信息部" :value="1" />
        <el-option label="人力资源部" :value="2" />
          <el-option label="财务部" :value="3" />
        <el-option label="销售部" :value="4" />
      </el-select>
    </el-form-item>



     <el-form-item label="请假类别" >
      <el-checkbox-group v-model="ruleForm.sortss">
        <el-checkbox value="事假" name="sorts">
         事假
        </el-checkbox>
        <el-checkbox value="病假" name="sorts">
          病假
        </el-checkbox>
        <el-checkbox value="婚假" name="sorts">
          婚假
        </el-checkbox>
        <el-checkbox value="丧假" name="sorts">
          丧假
        </el-checkbox>
        <el-checkbox value="产假" name="sorts">
         产假
        </el-checkbox>
        <el-checkbox value="补休" name="sorts">
          补休
        </el-checkbox>
        <el-checkbox value="工伤" name="sorts">
          工伤
        </el-checkbox>
        <el-checkbox value="其它" name="sorts">
          其它
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
   

            <el-form-item label="请假时间" >
                 <el-date-picker
                v-model="ruleForm.startTime"
                type="datetime"
                placeholder="请选择开始时间" @change="calculateTotalTime"
                />-
                <el-date-picker
                v-model="ruleForm.endTime"
                type="datetime"
                placeholder="请选择结束时间"
                @change="calculateTotalTime"
                />
              
                <el-col :span="15">共计{{ ruleForm.days }} </el-col>
                <br/><br/>

                 <el-form-item label="报道时间" >
                <el-date-picker
                v-model="ruleForm.reportTime"
                type="datetime"
                placeholder="请选择报道时间"
                />
            </el-form-item>
            </el-form-item>
            

    <el-form-item label="请假事由" prop="reason">
      <el-input v-model="ruleForm.reason" type="textarea" />
    </el-form-item>

     <el-form-item label="部门领导" prop="headName">
      <el-input v-model="ruleForm.headName"  :disabled="true"/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>

   <el-dialog v-model="dialogFormVisibleS" title="审批" width="800">
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px;"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="姓名" prop="appName">
      <el-input v-model="ruleForm.appName" :disabled="true" />
    </el-form-item>
     <el-form-item label="部门" prop="region">
      <el-select v-model="ruleForm.departmentId" placeholder="请选择部门" :disabled="true">
        <el-option label="IT信息部" :value="1" />
        <el-option label="人力资源部" :value="2" />
          <el-option label="财务部" :value="3" />
        <el-option label="销售部" :value="4" />
      </el-select>
    </el-form-item>
     <el-form-item label="请假类别" >
      <el-checkbox-group v-model="ruleForm.sortss">
        <el-checkbox value="事假" name="sorts">
         事假
        </el-checkbox>
        <el-checkbox value="病假" name="sorts">
          病假
        </el-checkbox>
        <el-checkbox value="婚假" name="sorts">
          婚假
        </el-checkbox>
        <el-checkbox value="丧假" name="sorts">
          丧假
        </el-checkbox>
        <el-checkbox value="产假" name="sorts">
         产假
        </el-checkbox>
        <el-checkbox value="补休" name="sorts">
          补休
        </el-checkbox>
        <el-checkbox value="工伤" name="sorts">
          工伤
        </el-checkbox>
        <el-checkbox value="其它" name="sorts">
          其它
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
            <el-form-item label="请假时间" >
                 <el-date-picker
                v-model="ruleForm.startTime"
                type="datetime"
                placeholder="请选择开始时间"
                />-
                <el-date-picker
                v-model="ruleForm.endTime"
                type="datetime"
                placeholder="请选择结束时间"
                />
              
                <el-col :span="15">共计{{ ruleForm.days }} </el-col>
                <br/><br/>

                 <el-form-item label="报道时间" >
                <el-date-picker
                v-model="ruleForm.reportTime"
                type="datetime"
                placeholder="请选择报道时间"
                />
            </el-form-item>
            </el-form-item>
    <el-form-item label="请假事由" prop="reason">
      <el-input v-model="ruleForm.reason" type="textarea" />
    </el-form-item>

     <el-form-item label="审核" >
       <el-radio-group v-model="ruleForm.state">
        <el-radio :value="0">通过</el-radio>
        <el-radio :value="1">拒绝</el-radio>
      </el-radio-group>&emsp13;&emsp13;
    
    </el-form-item>
<el-form-item 
  label="拒绝原因" 
  prop="approvalReason"
  v-if="ruleForm.state === 1"
>
  <el-input v-model="ruleForm.approvalReason" />
</el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitFormss(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>

</template>

<script lang="ts" setup>
import axios from 'axios';
import {ref,reactive,onMounted} from 'vue'
import moment from 'moment';
import {useCounterStore} from '@/stores/counter'
import Read from  '@/http/Readhttp'
import Write from '@/http/Writehttp'
const pinia=useCounterStore();
const tableData =ref([])
onMounted(()=>{
    getdata();
})
const getdata=()=>{
 
    Read.get("/api/Approval/ShowApp",{params:{
        PageIndex:pages.PageIndex,
        PageSize:pages.PageSize,
        Start:formInline.Start,
        End:formInline.End,
        ApprovalState:formInline.ApprovalState,
        AppName:formInline.AppName,
       Name:pinia.account.UserName
    }}).then(res=>{
    tableData.value=res.data.result
    pages.totalCount=res.data.totalCount
    pages.totalPage=res.data.totalPage
})
}

//部门
const departmentMap = reactive({
  1: 'IT信息部',
  2: '人力资源部',
  3: '财务部',
  4: '销售部'
});

const departname=(row:any)=>{
 return   (departmentMap as any)[row.departmentId] ;
}
//查询
const formInline = reactive({
  Start: '',
  End: '',
  ApprovalState: '',
  AppName:'',

})
import type { ComponentSize } from 'element-plus'
const size = ref<ComponentSize>('default')
const pages=reactive({
    PageIndex:1,
    PageSize:15,
    totalCount:0,
    totalPage:0
})
watch(pages,()=>{
  getdata()
})
//添加
const submitForms = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        ruleForm.sorts=ruleForm.sortss.join(',')
  
ruleForm.headName = Array.isArray(ruleForm.headName) 
  ? (ruleForm.headName.join(',') as unknown as never[]) 
  : []; 
    Write.post("/api/Approvals/AddApp",ruleForm).then(res=>{
        if(res.data.code==200)
    {
        ElMessage.success(res.data.msg);
        getdata();
        dialogFormVisible.value=false;
        ruleForm.reportTime='',
        ruleForm.endTime='',
        ruleForm.reason='',
        ruleForm.startTime='',
        ruleForm.totalTime=0,
        ruleForm.sortss=[],
        ruleForm.sorts=''
    }
    else{
        ElMessage.error(res.data.msg);
    }
    })
        
    } else {
      console.log('error submit!', fields)
    }
  })
}
//修改
const dialogFormVisible = ref(false)
const dialogFormVisibleedit = ref(false)
const dialogFormVisibleS = ref(false)
const update=(row:any)=>{
  dialogFormVisibleedit.value=true;
   let sorts = row.sorts; // 假设接口返回的字段是 sorts
  if (typeof sorts === 'string') {
  
ruleForm.sortss = sorts.split(',') as unknown as never[];  // 字符串转数组，绑定到 sortss
  } else {
    ruleForm.sortss = sorts || []; // 防止空值，兜底为空数组
  }
 
  Object.assign(ruleForm,row)
  calculateTotalTime();
}
import { watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules,ElMessageBox } from 'element-plus'


const ss = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
   "appName": pinia.account.UserName,
  "departmentId": pinia.account.departmentId,
  "sortss": [],
  "sorts": "",
  "startTime": "",
  "endTime": "",
  "totalTime": 0,
  "reportTime": "",
  "reason": "",
  "headName": pinia.account.names,
   "approvalReason": "",
  "approvalState": false,
  "state":3,
  days:''
})

const rules = reactive<FormRules>({
  reason: [
    { required: true, message: '请假事由不能为空', trigger: 'blur' },
    { min: 0, max: 140, message: '请假事由不能超过140个字', trigger: 'blur' },
  ],
 approvalReason: [
        
{ 
          required: true, 
          message: '拒绝时必须填写原因', 
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (ruleForm.state === 1 && !value) {
              callback(new Error('拒绝时必须填写原因'));
            } else {
              callback();
            }
          }
        }
      ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        ruleForm.sorts=ruleForm.sortss.join(',')
        
    Write.put("/api/Approvals/UpdateApp",ruleForm).then(res=>{
        if(res.data.code==200)
    {
        ElMessage.success(res.data.msg);
        getdata();
        dialogFormVisibleedit.value=false
    }
    else{
        ElMessage.error(res.data.msg);
    }
    })
        
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//计算时间
const calculateTotalTime = () => {
  if (!ruleForm.startTime || !ruleForm.endTime) return;

  const start = new Date(ruleForm.startTime);
  const end = new Date(ruleForm.endTime);

  // 校验结束时间不能小于开始时间
  if (end.getTime() < start.getTime()) {
    ElMessage.error("结束时间不能小于开始时间");
    ruleForm.endTime = '';
    return;
  }

  // 定义工作时间段 (9:00-17:00)
  const workStartHour = 9;
  const workEndHour = 17;
  const dailyWorkHours = 8;

  let totalHours = 0;
  let current = new Date(start);

  // 遍历每一天
  while (current <= end) {
    const currentDay = new Date(current);
    currentDay.setHours(0, 0, 0, 0);

    // 当天的工作开始时间
    const dayStart = new Date(currentDay);
    dayStart.setHours(workStartHour);
    
    // 当天的工作结束时间
    const dayEnd = new Date(currentDay);
    dayEnd.setHours(workEndHour);

    // 计算当天的工作时间段
    let segmentStart:any = current > dayStart ? current : dayStart;
    let segmentEnd:any = end < dayEnd ? end : dayEnd;

   // 如果是同一天且在工作时间内
    if (segmentStart < segmentEnd) {
      const hours = Math.floor((segmentEnd - segmentStart) / (1000 * 60 * 60)); // 取整小时数
      totalHours += hours > 0 ? hours : 0; // 确保不为负数
    }

    // 移动到下一天
    current = new Date(currentDay);
    current.setDate(current.getDate() + 1);
    current.setHours(workStartHour, 0, 0, 0);
  }

  // 计算完整工作天数和剩余小时数
  const fullDays = Math.floor(totalHours / dailyWorkHours);
  const remainingHours = totalHours % dailyWorkHours;

  // 更新显示
  ruleForm.days = `${fullDays}天${remainingHours}时`;
  ruleForm.totalTime = fullDays*8+remainingHours; // 总小时数
};


//删除
const del=(id:any) => {
  ElMessageBox.confirm(
    '确认删除吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
    Write.put("/api/Approvals/DelApp",{id:id}).then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.msg);
      getdata();
    }
    else{
      ElMessage.error(res.data.msg);
    }
  })
    })
}

const submitFormss = async (formEl: FormInstance | undefined) => {
  
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        ruleForm.sorts=ruleForm.sortss.join(',')
        
    Write.put("/api/Approvals/UpdateState",ruleForm).then(res=>{
        if(res.data.code==200)
    {
        ElMessage.success(res.data.msg);
        
        dialogFormVisibleS.value=false
        
    }
    else{
        ElMessage.error(res.data.msg);
    }
    getdata();
    })
        
    } else {
      console.log('error submit!', fields)
    }
  })
}

const UpdState=(row:any)=>{
  dialogFormVisibleS.value=true;
  let sorts = row.sorts; // 假设接口返回的字段是 sorts
  if (typeof sorts === 'string') {
   ruleForm.sortss = sorts.split(',') as unknown as never[]; // 字符串转数组，绑定到 sortss
  } else {
    ruleForm.sortss = sorts || []; // 防止空值，兜底为空数组
  }
 Object.assign(ruleForm,row)
 

}
</script>
<style scoped>
.demo-datetime-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}
.demo-datetime-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.demo-datetime-picker .block:last-child {
  border-right: none;
}
.demo-datetime-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
